<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="searchQuotaAlarmForm" :model="searchQuotaAlarmForm" label-width="80px">
        <el-col :span="5">
          <el-form-item style="margin-bottom: 5px;" label="设备号">
            <el-input v-model="searchQuotaAlarmForm.number" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item style="margin-bottom: 5px;" label="指标名">
            <el-input v-model="searchQuotaAlarmForm.name" />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-button style="margin-left:20px" type="primary" @click="searchPage">搜索</el-button>
        </el-col>
      </el-form>
    </div>
    <div class="table-container" :style="{width:'100%',overflow:'auto'}">
      <el-collapse v-model="activeName" accordion @change="handleChange">
        <template v-for="(item,idx) in quotaAlarmList">
          <el-collapse-item :key="idx" style="padding-bottom:0;" :name="idx">
            <template slot="title">
              <div style="width: 100%;">
                <el-row>
                  <el-col :span="2">指标ID: {{ item.id }}</el-col>
                  <el-col :span="3">指标名: {{ item.name }}</el-col>
                  <el-col :span="4">指标单位: {{ item.unit }}</el-col>
                  <el-col :span="4">主题: {{ item.subject }}</el-col>
                  <el-col :span="6">webhook: {{ item.webhook }}</el-col>
                  <el-col :span="4">参考值: {{ item.reference }}</el-col>
                </el-row>
                <el-row>
                  <el-col :offset="2" :span="3">设备ID: {{ item.deviceId }}</el-col>
                  <el-col :span="4">设备号: {{ item.number }}</el-col>
                  <el-col :span="4">{{ item.online ? '在线' : '离线' }}</el-col>
                  <el-col :span="6">监测状态：{{ item.status ? '开启' : '关闭' }}</el-col>
                </el-row>
              </div>
            </template>
            <el-row>
              <template v-if="item.alarmList.length>0">
                <el-table :data="item.alarmList" style="width:100%" border>
                  <el-table-column align="center" label="报警ID" width="80">
                    <template slot-scope="scope">
                      {{ scope.row.id }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="报警名" width="100">
                    <template slot-scope="scope">
                      {{ scope.row.name }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="operator" width="80">
                    <template slot-scope="scope">
                      {{ scope.row.operator }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="边界值" width="80">
                    <template slot-scope="scope">
                      {{ scope.row.threshold }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="报警等级" width="80">
                    <template slot-scope="scope">
                      {{ scope.row.level }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="webhook" width="150">
                    <template slot-scope="scope">
                      {{ scope.row.webhook }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="沉默周期" width="100">
                    <template slot-scope="scope">
                      {{ scope.row.cycle }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="操作" width="150" min-width="150">
                    <template slot-scope="scope">
                      <el-button type="primary" size="small" @click="handleUpdateQuotaAlarm(scope)">修改</el-button>
                      <el-button type="danger" size="small" @click="handleDeleteQuotaAlarm(scope)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
              <template v-else>
                <div style="width:100%;height:20px;text-align:center;">
                  <span style="color: #1f2d3d;font-size: 12px">暂未添加报警指标</span>
                </div>
              </template>
            </el-row>
            <el-row>
              <div align="center" style="margin: 0 auto;padding-top: 10px">
                <el-button size="small" type="primary" @click="handleAddQuotaAlarm">添加报警指标</el-button>
              </div>
            </el-row>
          </el-collapse-item>
        </template>
      </el-collapse>
      <el-dialog
        :visible.sync="dialogVisible"
        :title="dialogType==='edit'?'更新监控指标':'添加监控指标'"
      >
        <el-form
          ref="quotaAlarmForm"
          :model="quotaAlarmForm"
          :rules="(dialogType==='edit')?updateRules:addRules"
        >
          <el-row>
            <el-col :span="10">
              <el-form-item label="指标ID" label-width="100px" prop="quotaId">
                <el-input v-model="quotaAlarmForm.quotaId" disabled type="text" />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="指标名" label-width="70px" prop="quotaId">
                <el-input v-model="quotaAlarmForm.quotaName" disabled type="text" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="报警名" label-width="100px" prop="name">
              <el-input v-model="quotaAlarmForm.name" :disabled="dialogType==='edit'" type="text" placeholder="请输入报警名" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="operator" label-width="100px" prop="name">
              <el-select v-model="quotaAlarmForm.operator" style="width: 100px;" :disabled="dialogType==='edit'" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="边界值" label-width="100px" prop="valueKey">
              <el-col :span="8">
                <el-input v-model="quotaAlarmForm.threshold" type="text" placeholder="请输入边界值" />
              </el-col>
              <el-col :span="10">
                <span style="margin-left: 5px;color: #20a0ff;">{{ quotaAlarmForm.unit }}</span>
              </el-col>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="报警等级" label-width="100px" prop="valueType">
              <el-input v-model="quotaAlarmForm.level" type="text" placeholder="请输入报警等级" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="webhook" label-width="100px" prop="webhook">
              <el-input v-model="quotaAlarmForm.webhook" type="text" placeholder="请输入webhook" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="沉默周期" label-width="100px" prop="reference">
              <el-col :span="10">
                <el-input v-model="quotaAlarmForm.cycle" type="text" placeholder="沉默周期" />
              </el-col>
              <el-col :span="5">
                <span>小时</span>
              </el-col>
            </el-form-item>
          </el-row>

          <div style="text-align:right;">
            <el-button v-loading="loading" type="danger" @click="handleCancel">取消</el-button>
            <el-button v-loading="loading" type="primary" @click="confirm">确认</el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>

    <div class="page-container">
      <el-pagination
        :current-page="quotaAlarmPage.page"
        :page-size="quotaAlarmPage.pageSize"
        :page-count="quotaAlarmPage.pages"
        :total="quotaAlarmPage.counts"
        :pager-count="quotaAlarmPage.pageCount"
        align="center"
        layout="prev, pager, next, jumper"
        @current-change="handlePageChange"
        @prev-click="handlePageChange"
        @next-click="handlePageChange"
      />
    </div>
  </div>
</template>

<script>
import { findQuotaAlarmPage } from '@/api/quota'
import { addAlarm, delAlarm, updateAlarm } from '@/api/alarm'

const defaultQuotaAlarmPage = {
  page: 1,
  pageSize: 5,
  pageCount: 9
}
const defaultQuotaAlarmForm = {
  quotaId: '',
  quotaName: '',
  name: '',
  operator: '',
  threshold: '',
  unit: '',
  level: '',
  cycle: '',
  webhook: ''
}
export default {
  name: 'QuotaAlarm',
  data() {
    return {
      loading: false,
      listLoading: true,
      dialogType: 'new',
      dialogVisible: false,
      quotaAlarmForm: Object.assign({}, defaultQuotaAlarmForm),
      Height: '',
      activeName: '1',
      options: [
        { key: 0, value: '<', label: '<' },
        { key: 1, value: '>', label: '>' }
      ],
      searchQuotaAlarmForm: { number: '', name: '' },
      quotaAlarmPage: Object.assign({}, defaultQuotaAlarmPage),
      quotaAlarmList: [],
      addRules: {
        quotaId: [{ required: true, message: '请输入指标ID', trigger: 'blur' }],
        name: [{ required: true, message: '请输入报警名', trigger: 'blur' }],
        operator: [{ required: true, message: '请输入operator', trigger: 'blur' }],
        threshold: [{ required: true, message: '请输入边界值', trigger: 'blur' }],
        level: [{ required: true, message: '请输入报警等级', trigger: 'blur' }],
        cycle: [{ required: true, message: '请输入沉默周期', trigger: 'blur' }],
        webhook: [{ required: true, message: '请输入webhook', trigger: 'blur' }]
      },
      updateRules: {
        threshold: [{ required: true, message: '请输入边界值', trigger: 'blur' }],
        level: [{ required: true, message: '请输入报警等级', trigger: 'blur' }],
        cycle: [{ required: true, message: '请输入沉默周期', trigger: 'blur' }],
        webhook: [{ required: true, message: '请输入webhook', trigger: 'blur' }]
      }
    }
  },
  watch: {
    '$route.query': {
      handler(newVal, oldVal) {
        console.log('newQuery', newVal)
        const query = this.$route.query
        if (Object.keys(newVal).length !== Object.keys(oldVal).length || (
          newVal.tag !== oldVal.tag || newVal.number !== oldVal.number || newVal.state !== oldVal.state
        )) {
          newVal.page = 1
          newVal.pageSize = 10
        }
        if (query.number) this.searchQuotaAlarmForm.number = query.number
        if (query.name) this.searchQuotaAlarmForm.name = query.name
        findQuotaAlarmPage(query).then(response => {
          // console.log('pager', response.data.pager)
          this.updatePage(response.data.pager)
        })
        this.activeName = '1'
      },
      deep: true
    }
  },
  created() {
    const query = this.$route.query
    let data = {}
    if (query) {
      if (query.page) data.page = parseInt(query.page)
      if (query.pageSize) data.pageSize = parseInt(query.pageSize)
      if (query.number) data.number = this.searchQuotaAlarmForm.number = query.number
      if (query.name) data.tag = this.searchQuotaAlarmForm.name = query.name
    } else {
      data = { page: 1, pageSize: 10 }
    }
    findQuotaAlarmPage(data).then(response => {
      console.log('pager', response.data.pager)
      this.updatePage(response.data.pager)
    })
  },
  mounted() {
    document.getElementsByClassName('el-pagination__jump')[0].childNodes[0].nodeValue = '跳转第'
    document.getElementsByClassName('el-pagination__jump')[0].insertAdjacentText('beforeend', '页')
  },
  methods: {
    async delQuotaAlarm(index, row) {
      console.log('row', row)
      await delAlarm(row)
      console.log('index', index)
      const data = this.quotaAlarmList[parseInt(this.activeName)]
      data.alarmList.splice(index, 1)
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
    },
    addQuotaAlarm() {
      this.$refs.quotaAlarmForm.validate(async valid => {
        if (valid) {
          this.loading = true
          // console.log('quotaAlarmForm', this.quotaAlarmForm)
          await addAlarm(this.quotaAlarmForm).then(response => {
            const alarm = response.data.alarm
            console.log('alarm', alarm)
            const data = this.quotaAlarmList[parseInt(this.activeName)]
            data.alarmList.push(alarm)
          })
          this.loading = false
        } else {
          console.log('error update!!')
          return false
        }
      })
    },
    updateQuotaAlarm() {
      this.$refs.quotaAlarmForm.validate(valid => {
        if (valid) {
          this.loading = true
          updateAlarm(this.quotaAlarmForm)
          this.loading = false
        } else {
          console.log('error update!!')
          return false
        }
      })
    },
    handleAddQuotaAlarm() {
      this.dialogType = 'new'
      this.quotaAlarmForm = Object.assign({}, defaultQuotaAlarmForm)
      const data = this.quotaAlarmList[parseInt(this.activeName)]
      this.quotaAlarmForm.quotaId = data.id
      this.quotaAlarmForm.quotaName = data.name
      this.quotaAlarmForm.unit = data.unit
      this.dialogVisible = true
      // console.log('handleAdd', this.quotaAlarmForm)
    },
    handleUpdateQuotaAlarm(scope) {
      this.dialogType = 'edit'
      const data = this.quotaAlarmList[parseInt(this.activeName)]
      this.quotaAlarmForm = Object.assign({}, defaultQuotaAlarmForm)
      for (const key of Object.keys(this.quotaAlarmForm)) {
        if (scope.row[key]) this.quotaAlarmForm[key] = scope.row[key]
      }
      this.quotaAlarmForm.quotaId = scope.row.id
      this.quotaAlarmForm.quotaName = data.name
      this.quotaAlarmForm.unit = data.unit
      // console.log('handle-update', data, this.quotaAlarmForm)
      this.dialogVisible = true
    },
    handleDeleteQuotaAlarm({ $index, row }) {
      this.$confirm('是否移除该报警?', 'Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await this.delQuotaAlarm($index, row)
      }).catch(err => {
        console.error(err)
      })
    },
    handleCancel() {
      this.quotaAlarmForm = Object.assign({}, defaultQuotaAlarmForm)
      this.dialogVisible = false
    },
    async confirm() {
      const isEdit = this.dialogType === 'edit'
      console.log('quotaAlarmForm', this.quotaAlarmForm)
      if (!isEdit) {
        await this.addQuotaAlarm()
      } else {
        await this.updateQuotaAlarm()
        let flag = true
        for (let i = 0; flag && i < this.quotaAlarmList.length; i++) {
          if (this.quotaAlarmList[i].id === this.quotaAlarmForm.quotaId) {
            const list = this.quotaAlarmList[i].alarmList
            console.log('list', list)
            for (let j = 0; flag && j < list.length; j++) {
              if (this.quotaAlarmForm.name === list[j].name &&
                this.quotaAlarmForm.operator === list[j].operator) {
                this.quotaAlarmList[i].alarmList[j].threshold = this.quotaAlarmForm.threshold
                this.quotaAlarmList[i].alarmList[j].level = this.quotaAlarmForm.level
                this.quotaAlarmList[i].alarmList[j].cycle = this.quotaAlarmForm.cycle
                this.quotaAlarmList[i].alarmList[j].webhook = this.quotaAlarmForm.webhook
                flag = false
              }
            }
          }
        }
      }
      this.dialogVisible = false
    },
    searchPage() {
      let data = Object.assign({}, this.searchQuotaAlarmForm)
      data = Object.assign(data, this.quotaAlarmPage)
      delete data['counts']
      this.$router.replace({
        path: this.$route.path,
        query: this.simplify(data)
      })
    },
    updatePage(pager) {
      this.quotaAlarmPage = {
        page: pager.page,
        pages: pager.pages,
        pageSize: pager.pageSize,
        counts: pager.counts
      }
      this.quotaAlarmList = pager.items
      this.listLoading = false
    },
    simplify(obj) {
      const res = Object.assign({}, obj)
      for (const key of Object.keys(res)) {
        if (res[key] === '') delete res[key]
      }
      return res
    },
    handlePageChange(param) {
      this.quotaAlarmPage.page = param
      const data = Object.assign({}, this.quotaAlarmPage)
      delete data['counts']
      if (this.searchQuotaAlarmForm.number) data.number = this.searchQuotaAlarmForm.number
      if (this.searchQuotaAlarmForm.name) data.name = this.searchQuotaAlarmForm.name
      this.$router.replace({
        path: this.$route.path,
        query: this.simplify(data)
      })
    },
    handleChange(val) {
      // console.log('val', val)
    }
  }
}
</script>

<style scoped>

.search-container {
  width: 100%;
  height: 50px;
}

.table-container {
  width: 100%;
}

.page-container {
  width: 100%;
}

/deep/ .el-collapse-item__header {
  height: 65px;
  line-height: 30px;
}

/deep/ .el-collapse-item__content {
  padding-bottom: 5px;
  font-size: 13px;
  color: #FFFFFF;
}

</style>
